package com.wetool.spec.invoicing;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import com.wetool.entity.invoicing.InventoryRecord;
import com.wetool.model.invoicing.SearchParam;
import com.wetool.service.invoicing.TypeService;

public class InventoryRecordSpec implements Specification<InventoryRecord> {

	private final SearchParam example;

	//private StorageTypeService storageTypeService;

	public InventoryRecordSpec(SearchParam example) {
		this.example = example;
	}

	public InventoryRecordSpec(SearchParam example, TypeService typeService) {
		this.example = example;
		//this.storageTypeService = storageTypeService;
	}

	@Override
	public Predicate toPredicate(Root<InventoryRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		List<Predicate> predicates = new ArrayList<Predicate>();
		/* 查询店铺Id */
		Predicate pred = null;
		predicates.add(cb.and(cb.equal(root.get("isDeleted"), false)));
		predicates.add(cb.and(cb.equal(root.get("shopId"), example.getShopId())));
		if (StringUtils.isNotEmpty(example.getKey())) {
			pred =cb.or(cb.equal(cb.lower(root.get("orderNumber")),  example.getKey() ));
			pred = cb.or(pred, cb.equal(cb.lower(root.get("initialOrderNumber")), example.getKey() ));
			predicates.add(pred);
		}
		predicates.add(cb.and(cb.equal(root.get("outOfStorage"), example.getOutOfStorage())));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 7L)));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 8L)));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 13L)));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 2L)));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 2L)));
		predicates.add(cb.and(cb.notEqual(root.get("type"), 5L)));
		/*出入库单号类型*/
		if (example.getTypeId() != null) {
			pred = cb.and(cb.equal(root.get("type"), example.getTypeId()));
			predicates.add(pred);
		}
		/*出入库单状态*/ 
		if (example.getStatus() != null) {
			pred = cb.and(cb.equal(root.get("status"), example.getStatus()));
			predicates.add(pred);
		}
		/* 供应商 */
		if (example.getSupplierId() != null) {
			pred = cb.and(cb.equal(root.get("supplierId"), example.getSupplierId()));
			predicates.add(pred);
		}
		return andTogether(predicates, cb);
	}

	private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
		return cb.and(predicates.toArray(new Predicate[0]));
	}

}
